package com.whzykj.resource;

import java.math.BigDecimal;
import java.sql.Timestamp;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.jfinal.aop.Before;
import com.jfinal.kit.StrKit;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.activerecord.Record;
import com.jfinal.plugin.activerecord.tx.Tx;
import com.whzykj.common.CommonUtils;
import com.whzykj.common.DateUtil;
import com.whzykj.common.DictCache;
import com.whzykj.common.JsonUtil;
import com.whzykj.common.ReturnEnum;
import com.whzykj.common.SystemRunParamCache;
import com.whzykj.model.OrderDetails;
import com.whzykj.model.OrderInfo;
import com.whzykj.model.Userinfo;

import net.sf.json.JSONObject;

public class OrderResource {
	/**
	 * 设置能够下订单的有效时间段
	 * 
	 * @return
	 */
	private boolean isValidTime() {
		boolean valid = false; // 表示在非有效时间段
		// 判断下单的时间是否在禁止下单时间内操作
		SimpleDateFormat dfs = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		String order_end_time = SystemRunParamCache.cache
				.getParamValue("order_end_time"); // 从缓存中获取订单截止时间（格式：19:30:00）
		String order_start_time = SystemRunParamCache.cache
				.getParamValue("order_start_time"); // 从缓存中获取订单开始时间（格式：23:59:59）
		String today = DateUtil.getToday();
		String startTime = today + " 19:30:00"; // 订单截止下单时间（禁止下单开始时间）
		String endTime = today + " 23:59:59"; // 订单开始下单时间（禁止下单结束时间）
		if (order_end_time != null && !order_end_time.equals("")) {
			startTime = today + " " + order_end_time;
		}
		if (order_start_time != null && !order_start_time.equals("")) {
			endTime = today + " " + order_start_time;
		}
		try {
			java.util.Date start = dfs.parse(startTime);
			java.util.Date end = dfs.parse(endTime);
			java.util.Date now = new java.util.Date();
			long s = start.getTime();
			long e = end.getTime();
			long n = now.getTime();
			if (n >= s && n <= e) {
				valid = false;
			} else {
				valid = true;
			}
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			valid = false;
		}
		// 以上判断禁止下单操作结束
		return valid;
	}

	/****
	 * 生成订单
	 * 
	 * @param messageObj
	 * @param result
	 *            http://localhost:8080/bcy/mobile/Interface?content={namespace:
	 *            'order',type:'addorderinfo',user_id:'23',order_pay_detail:[{"num":"1","goods_id":"1"},{"num":"1","goods_id":"2"}
	 *            ] }
	 */
	@SuppressWarnings("unchecked")
	@Before(Tx.class)
	public void addorderinfo(JSONObject messageObj, JSONObject result) {
		// 在非有效时间内下单，直接返回错误信息提示
		if (!isValidTime()) {
			JsonUtil.put(result, ReturnEnum.ORDER_TIME_FAIL);
			return;
		}
		/*
		 * System.out.println("Orderinfo:Hello world"); String orderid =
		 * CommonUtils.generateSeq(); String userid =
		 * messageObj.getString("user_id"); // 商品明细 Object goodsobj =
		 * messageObj.get("order_pay_detail");
		 * 
		 * Userinfo userinfo = Userinfo.dao.findById(userid); int custid =
		 * userinfo.getInt("cust_id");
		 * 
		 * OrderInfo orderInfo = new OrderInfo();
		 * 
		 * orderInfo.set("order_id", orderid); orderInfo.set("user_id", userid);
		 * orderInfo.set("order_date", new Date()); orderInfo.set("take_date",
		 * CommonUtils.parseDate(CommonUtils
		 * .getSpecifiedDayAfter(CommonUtils.getCurrentDate())));
		 * orderInfo.set("cust_id", custid);
		 * 
		 * BigDecimal ordermoney = new BigDecimal("0.00");// 订单金额 BigDecimal
		 * minusmoney = new BigDecimal("0.00");// 优惠金额 BigDecimal realmoney =
		 * new BigDecimal("0.00");// 实付金额 List<Map<String, Object>>
		 * orderPayDetails = JsonUtil.getList4Json(goodsobj.toString(),
		 * Map.class);
		 * 
		 * synchronized(orderPayDetails){ for (Map<String, Object>
		 * orderPayDetail : orderPayDetails) { OrderDetails details = new
		 * OrderDetails();
		 * 
		 * String goodsid = orderPayDetail.get("goods_id").toString(); String
		 * num = orderPayDetail.get("num").toString();
		 * 
		 * Record storeRd = getStoreById(goodsid); int store_num =
		 * storeRd.getInt("store_num"); int sale_num =
		 * storeRd.getInt("sale_num"); int stack = store_num - sale_num;// 剩余库存
		 * int limit_num = storeRd.getInt("limit_num"); if (stack <= 0 || stack
		 * < (Integer.parseInt(num)) || (Integer.parseInt(num)) > limit_num) {
		 * result.put("goods_id", goodsid); JsonUtil.put(result,
		 * ReturnEnum.ORDER_ADD_FAIL); return; }
		 * 
		 * sale_num = sale_num + Integer.parseInt(num); int countstack =
		 * updateStoreById(goodsid, sale_num); if (countstack == 0) {
		 * result.put("goods_id", goodsid); JsonUtil.put(result,
		 * ReturnEnum.ORDER_ALLOW_FAIL); return; }
		 * 
		 * // 查询价格 // Record pricerd = getPriceById(goodsid); Record pricerd =
		 * getPriceById(goodsid, userid); BigDecimal sale_price =
		 * pricerd.getBigDecimal("sale_price"); BigDecimal minus_price =
		 * pricerd.getBigDecimal("minus_price"); int count =
		 * minus_price.compareTo(BigDecimal.ZERO); BigDecimal numbe = new
		 * BigDecimal(num);// 数量 if (count == 0) { BigDecimal paraDe1 =
		 * sale_price.multiply(numbe); ordermoney = ordermoney.add(paraDe1);//
		 * 原价 realmoney = realmoney.add(paraDe1);// 实价 details.set("SALE_PRICE",
		 * sale_price); } else { BigDecimal paraDe1 =
		 * sale_price.multiply(numbe);// 原总价 BigDecimal paraDe2 =
		 * minus_price.multiply(numbe);// 优惠后总价 BigDecimal minus =
		 * paraDe1.subtract(paraDe2);// 原总价-优惠后总价=优惠金额 minusmoney =
		 * minusmoney.add(minus);// 计算优惠金额
		 * 
		 * ordermoney = ordermoney.add(paraDe1);// 原价 realmoney =
		 * realmoney.add(paraDe2);// 实价
		 * 
		 * details.set("SALE_PRICE", minus_price); }
		 * 
		 * details.set("order_id", orderid); details.set("goods_id", goodsid);
		 * details.set("ORIGINAL_PRICE", sale_price); details.set("SALE_NUM",
		 * num); details.save(); } }
		 * 
		 * orderInfo.set("total_amounts", ordermoney);
		 * orderInfo.set("MINUS_AMOUNTS", minusmoney);
		 * orderInfo.set("PAY_AMOUNTS", realmoney);
		 * orderInfo.set("FREIGHT_AMOUNTS", "0.00");
		 * orderInfo.set("PAY_METHODS", "10");// 10 线下支付 orderInfo.set("STATUS",
		 * "no_pay"); orderInfo.set("ORDER_INFO", ""); orderInfo.set("REMARKS",
		 * ""); orderInfo.save(); result.put("order_id", orderid);
		 * JsonUtil.put(result, ReturnEnum.ORDER_ADD_SUCCESS);
		 */

		String orderid = OrderManager.getInstance().addorderinfo(messageObj,
				result);
		if (orderid == null) {
			JsonUtil.put(result, ReturnEnum.ORDER_ADD_FAIL);
			return;
		} else {
			result.put("order_id", orderid);
			JsonUtil.put(result, ReturnEnum.ORDER_ADD_SUCCESS);
		}
	}

	/****
	 * 计算费用
	 * 
	 * @param messageObj
	 * @param result
	 *            http://localhost:8080/bcy/mobile/Interface?content={namespace:
	 *            'order',type:'charge',user_id:'1',order_pay_detail:[{"num":"1","goods_id":"1"},{"num":"1","goods_id":"2"}
	 *            ] }
	 */
	@SuppressWarnings("unchecked")
	public void charge(JSONObject messageObj, JSONObject result) {
		String user_id = messageObj.getString("user_id");
		// 商品明细
		Object goodsobj = messageObj.get("order_pay_detail");

		BigDecimal ordermoney = new BigDecimal("0.00");// 订单金额
		BigDecimal minusmoney = new BigDecimal("0.00");// 优惠金额
		BigDecimal realmoney = new BigDecimal("0.00");// 实付金额

		List<Map<String, Object>> orderPayDetails = JsonUtil.getList4Json(
				goodsobj.toString(), Map.class);
		for (Map<String, Object> orderPayDetail : orderPayDetails) {
			String goodsid = orderPayDetail.get("goods_id").toString();
			String num = orderPayDetail.get("num").toString();
			// 查询价格
			Record pricerd = getPriceById(goodsid);
			BigDecimal sale_price = pricerd.getBigDecimal("sale_price");
			BigDecimal minus_price = pricerd.getBigDecimal("minus_price");
			int count = minus_price.compareTo(BigDecimal.ZERO);
			BigDecimal numbe = new BigDecimal(num);// 数量
			if (count == 0) {
				BigDecimal paraDe1 = sale_price.multiply(numbe);
				ordermoney = ordermoney.add(paraDe1);// 原价
				realmoney = realmoney.add(paraDe1);// 实价
			} else {
				BigDecimal paraDe1 = sale_price.multiply(numbe);// 原总价
				BigDecimal paraDe2 = minus_price.multiply(numbe);// 优惠后总价
				BigDecimal minus = paraDe1.subtract(paraDe2);// 原总价-优惠后总价=优惠金额
				minusmoney = minusmoney.add(minus);// 计算优惠金额

				ordermoney = ordermoney.add(paraDe1);// 原价
				realmoney = realmoney.add(paraDe2);// 实价
			}
		}
		result.put("ordermoney", ordermoney);// //免赔金优惠金额
		result.put("minusmoney", minusmoney);
		result.put("realmoney", realmoney);
		result.put("user_id", user_id);
		JsonUtil.put(result, ReturnEnum.RETURN_SUCCESS);
	}

	/****
	 * 订单列表
	 * 
	 * @param messageObj
	 * @param result
	 *            http://localhost:8080/bcy/mobile/Interface?content={namespace:
	 *            'order', "type":"list", "user_id":"50", "order_id":"", "page_current":"1", "page_size":"10"}
	 * @throws ParseException 
	 */
	public void list(JSONObject messageObj, JSONObject result){
		String userid = messageObj.getString("user_id");
		Object orderobj = messageObj.get("order_id");
		String orderid = "";
		if (orderobj != null && !"".equals(orderobj)) {
			orderid = orderobj.toString();
		}
		
		Object pageCurrent = messageObj.get("page_current");
        if(pageCurrent == null)
        {
        	pageCurrent="1";
        }
        Object page_size = messageObj.get("page_size");
        if(page_size == null || "".equals(page_size))
        {
        	page_size="50";
        }
        
        String sqlBefore = " select *  ";
        
        StringBuffer sbf = new StringBuffer();
		sbf.append(" FROM orderinfo where 1=1 ");
		if (userid != null && !"".equals(userid)) {
			sbf.append(" and user_id=" + userid + " ");
		}
		if (orderid != null && !"".equals(orderid)) {
			sbf.append(" and order_id='" + orderid + "' ");
		}
		sbf.append(" order by order_date desc ");
		Page<Record> paginate = Db.paginate(Integer.parseInt(pageCurrent.toString()), Integer.parseInt(page_size.toString()), sqlBefore,sbf.toString());
		
		List<Record> orderlist = paginate.getList();//OrderInfo.me.getOrder(userid, orderid);
		List<Map<String, Object>> dataList = new ArrayList<Map<String, Object>>();
		if (orderlist != null && orderlist.size() > 0) {
			for (Record record : orderlist) {
				Date orderdate = record.getDate("order_date");
				String status = record.getStr("status");
				String statusname = DictCache.cache.getDicByText(status);
				String order_id = record.getStr("order_id");

				Map<String, Object> dataMap = new HashMap<String, Object>();
				dataMap.put("status", status);
				dataMap.put("status_name", statusname);
				dataMap.put("order_id", order_id);
				dataMap.put("order_date", CommonUtils.getDateStr(orderdate));
				
				String up_time=SystemRunParamCache.cache.getLastOrderPaytime(CommonUtils.getDateStr(orderdate));
				dataMap.put("up_time", CommonUtils.dateForString(CommonUtils.strparseDate(up_time),"HH:mm"));//截止时间
				
				// 查询订单后所包含商品
				List<Record> detailList = OrderDetails.me.getOrderDetail(order_id);
				for (Record rd : detailList) {
					BigDecimal sale_price = rd.getBigDecimal("sale_price");
					int num = rd.getInt("sale_num");
					BigDecimal paraDe1 = sale_price.multiply(new BigDecimal(num));
					rd.set("real_pay", paraDe1);
				}
				dataMap.put("goods_detail",JsonUtil.getJsonObjByjfinalList(detailList));
				
				dataList.add(dataMap);
			}
			result.put("order", dataList);
			JsonUtil.put(result, ReturnEnum.ORDER_LIST_SUCCESS);
		} else {
			result.put("user_id", userid);
			JsonUtil.put(result, ReturnEnum.RETURN_SUCCESS_NODATA);
		}
	}

	/****
	 * 订单详情
	 * 
	 * @param messageObj
	 * @param result
	 *            http://localhost:8080/bcy/mobile/Interface?content={namespace:
	 *            'order',type:'orderdetail',user_id:'1',order_id:'APP20160630171228198
	 *            ' }
	 */
	public void orderdetail(JSONObject messageObj, JSONObject result) {
		String userid = messageObj.getString("user_id");
		Object orderobj = messageObj.get("order_id");
		String orderid = "";
		Date take_date = null;
		if (orderobj != null && !"".equals(orderobj)) {
			orderid = orderobj.toString();
		}
		List<OrderInfo> orderlist = OrderInfo.me.getOrder(userid, orderid);
		List<Map<String, Object>> dataList = new ArrayList<Map<String, Object>>();
		if (orderlist != null && orderlist.size() > 0) {
			for (OrderInfo orderInfo : orderlist) {
				Date orderdate = orderInfo.getDate("order_date");
				take_date = orderInfo.getDate("take_date");
				String status = orderInfo.getStr("status");
				String statusname = DictCache.cache.getDicByText(status);
				String order_id = orderInfo.getStr("order_id");

				Map<String, Object> dataMap = new HashMap<String, Object>();
				dataMap.put("status", status);
				dataMap.put("status_name", statusname);
				dataMap.put("order_id", order_id);
				dataMap.put("order_date", CommonUtils.getDateStr(orderdate));
				dataMap.put("total_amounts",
						orderInfo.getBigDecimal("total_amounts"));
				dataMap.put("minus_amounts",
						orderInfo.getBigDecimal("minus_amounts"));
				dataMap.put("pay_amounts",
						orderInfo.getBigDecimal("pay_amounts"));
				String up_time=SystemRunParamCache.cache.getLastOrderPaytime(CommonUtils.getDateStr(orderdate));
				dataMap.put("up_time", CommonUtils.dateForString(CommonUtils.strparseDate(up_time),"HH:mm"));//截止时间
				dataList.add(dataMap);

			}
			result.put("order", dataList);

			// 查询订单后所包含商品
			List<Record> detailList = OrderDetails.me.getOrderDetail(orderid);
			for (Record rd : detailList) {
				BigDecimal sale_price = rd.getBigDecimal("sale_price");
				int num = rd.getInt("sale_num");
				BigDecimal paraDe1 = sale_price.multiply(new BigDecimal(num));
				rd.set("real_pay", paraDe1);
			}
			result.put("goods_detail",
					JsonUtil.getJsonObjByjfinalList(detailList));
			// 提货人信息
			Record userRd = Userinfo.dao.getUserInfo(userid);
			if (userRd != null) {
				userRd.set("take_date", take_date);
				result.put("take_detail", JsonUtil.getMapByJfinalRecord(userRd));
				int station_id = userRd.getInt("station_id");
				Record statRd = Userinfo.dao.getUserStationById(String
						.valueOf(station_id));
				if (statRd != null) {
					result.put("station_detail",
							JsonUtil.getMapByJfinalRecord(statRd));
				} else {
					result.put("station_detail", "");
				}
			} else {
				result.put("take_detail", "");
			}

			//余额信息
			if (userRd != null) {
				String acctsql=" SELECT a.* FROM account a,userinfo b WHERE a.cust_id=b.cust_id and b.userid =? ";
				Record balanceRd = Db.findFirst(acctsql,userid);
				if(balanceRd==null){
					result.put("balances_detail", "");
				}else{
					String state = balanceRd.getStr("state");
					if(StrKit.isBlank(state)){
						result.put("balances_detail", "");
					}else{
						result.put("balances_detail", JsonUtil.getMapByJfinalRecord(balanceRd));
					}
				}
			}else{
				result.put("balances_detail", "");
			}
			JsonUtil.put(result, ReturnEnum.ORDERDETAIL_LIST_SUCCESS);
		} else {
			result.put("user_id", userid);
			JsonUtil.put(result, ReturnEnum.RETURN_SUCCESS_NODATA);
		}
	}

	/****
	 * 查询商品价格
	 * 
	 * @param goods_id
	 * @return
	 */
	private Record getPriceById(String goods_id) {
		if (goods_id == null || "".equals(goods_id))
			return null;
		String couponQry = " select * from price where goods_id = ? and date(set_date) = curdate() ";
		Record rd = Db.findFirst(couponQry, goods_id);
		if (rd == null) {
			couponQry = " select * from price where goods_id = ? order by set_date desc ";
			rd = Db.findFirst(couponQry, goods_id);
		}
		return rd;
	}

	/**
	 * 查询指定站点的商品当天的价格
	 * 
	 * @param goods_id
	 * @param userid
	 * @return
	 */
	private Record getPriceById(String goods_id, String userid) {
		if (goods_id == null || "".equals(goods_id))
			return null;
		String couponQry = null;
		StringBuffer sql = new StringBuffer(
				" select * from price where goods_id = ? and date(set_date) = curdate()");
		sql.append(" AND STATION_ID IN(");
		sql.append(" SELECT TAKE_STATION_ID from customer where CUST_ID IN(");
		sql.append(" select CUST_ID from userinfo where USERID=?))");
		Record rd = Db.findFirst(sql.toString(), goods_id, userid);
		if (rd == null) {
			couponQry = " select * from price where goods_id = ? order by set_date desc ";
			rd = Db.findFirst(couponQry, goods_id);
		}
		return rd;
	}

	/****
	 * 查询商品库存
	 * 
	 * @param goods_id
	 * @return
	 */
	private Record getStoreById(String goods_id) {
		if (goods_id == null || "".equals(goods_id))
			return null;
		String couponQry = " select * from store where goods_id = ? and date(set_date) = curdate() ";
		Record rd = Db.findFirst(couponQry, goods_id);
		return rd;
	}

	/****
	 * 查询商品库存
	 * 
	 * @param goods_id
	 * @return
	 */
	private int updateStoreById(String goods_id, int num) {
		if (goods_id == null || "".equals(goods_id))
			return 0;
		String couponQry = " update store set sale_num=? where goods_id = ? and date(set_date) = curdate() ";
		int count = Db.update(couponQry, num, goods_id);
		return count;
	}

	public static void main(String[] args) {
		BigDecimal minus_price = new BigDecimal("0.01");
		int count = minus_price.compareTo(BigDecimal.ZERO);
		System.out.println(count);

		JSONObject json = new JSONObject();

		List<Map<String, Object>> payLst = new ArrayList<Map<String, Object>>();

		Map<String, Object> data1 = new HashMap<String, Object>();
		data1.put("goods_id", "1");
		data1.put("num", "1");
		payLst.add(data1);

		Map<String, Object> data2 = new HashMap<String, Object>();
		data2.put("goods_id", "2");
		data2.put("num", "1");
		// payLst.add(data2);

		json.put("order_pay_detail", payLst);
		System.out.println(json.toString());

	}

}
